<template>
  <el-card>
    <div slot="header">
      <h3>批量恢复供货</h3>
    </div>
    <div>
      <el-row type="flex" justify="center">
        <h4 class="warning_title">恢复供货后，需及时维护进价！</h4>
      </el-row>
      <el-row type="flex" justify="end">
        <el-button
          v-show="showBtn('高级关联')"
          type="text"
          size="large"
          icon="el-icon-link"
          @click="handleSeniorLinked"
        >高级关联</el-button
        >
        <el-button
          v-show="showBtn('关联商品')"
          type="text"
          size="large"
          @click="handleGoodsLinked"
        >关联商品</el-button
        >
        <el-button
          type="text"
          size="large"
          :loading="btnLoading.submit"
          @click="handleSubmit"
        >提交</el-button
        >
        <el-button
          type="text"
          size="large"
          @click="$router.push({ name: 'delsupplyInfo' })"
        >返回</el-button
        >
      </el-row>
      <!-- 发起原因输入框 -->
      <LaunchReasonInput :reason.sync="launchReason" />
      <el-row class="format_table_wrap">
        <SkusTable
          :loading="tableInfo.loading"
          :columns="tableInfo.columns"
          :dataSource="tableInfo.list"
          :defaultMinWidth="120"
          @handleCancelSelect="handleDeleteTableRow"
        />
      </el-row>
      <FooterFields :footerFields="footerFields" />
    </div>
    <!-- 关联商品弹框组件 -->
    <AssociatedDialog
      :visible.sync="goodsLinked.visible"
      :columns="goodsLinked.columns"
      :formInfo="goodsLinked.formInfo"
      :requestApi="goodsLinked.requestApi"
      :distinctParams="goodsLinked.distinctParams"
      :dimensionKey="goodsLinked.dimensionKey"
      :closeRestFormFlag="false"
      @handleSubmit="getTableDataByGoodsLinked"
    />
    <!-- 高级关联弹框 -->
    <SeniorLinkedDialog
      :visible.sync="seniorLinked.visible"
      :columns="seniorLinked.columns"
      :dataSource="seniorLinked.dataSource"
      @seniorSearchResult="getTableDataBySeniorLinked"
    />
  </el-card>
</template>
<script>
import { ApiRequest } from '@api/basePage';
import { getBtnsId } from '@/libs/btnsPermission';
import { mapState, mapGetters, mapMutations } from 'vuex';
import { tableColumns, associatedTableColumns, formItemList } from './constants';
import SkusTable from '@/components/skusTable';
import AssociatedDialog from '../components/batchSupply/associatedDialog';
import SeniorLinkedDialog from '@/components/SeniorLinkedDialog';
import FooterFields from '@/pages/commodity/components/FooterFields';
import LaunchReasonInput from '@/components/LaunchReasonInput';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
import { getListByMapDimensionKey } from '@/utils/getUtils';
import { BATCH_RESTORE_SUPPLY } from '@/constants/exportAmountLimit';
export default {
  components: {
    SkusTable,
    AssociatedDialog,
    SeniorLinkedDialog,
    FooterFields,
    LaunchReasonInput
  },
  data () {
    return {
      footerFields: {}, // 表尾字段
      launchReason: '', // 发起原因
      seniorLinked: {
        visible: false,
        columns: [
          { label: '供应商编码', prop: 'supplyCode', type: 'textarea' },
          { label: 'SKU编码', prop: 'skuNo', type: 'textarea' }
        ],
        dataSource: [{ supplyCode: '', skuNo: '' }],
        isSenior: false // 当前是高级关联操作
      },
      tableInfo: {
        loading: false,
        list: [],
        columns: tableColumns
      },
      btnLoading: { // 按钮loading
        submit: false // 提交
      },
      goodsLinked: {
        visible: false,
        dimensionKey: 'uuid',
        columns: associatedTableColumns,
        formItemList: formItemList,
        formInfo: {
          itemList: formItemList,
          dataSource: {
            supplyUuid: '',
            supplyName: '',
            spuNo: '',
            skuNo: '',
            productName: '',
            saleCityName: ''
          }
        },
        requestApi: {
          url: '/sysback/supplyarea/getNeedRecoverSupplyRelProductList',
          type: 'post'
        },
        distinctParams: {
          notAssociated: 'uuidNotInSet',
          associated: 'uuidInSet'
        },
      },
      apiObj: {
        getTableData: { // 获取表格数据
          url: '/sysback/supplyarea/getNeedRecoverSupplyRelProductSelectedList',
          type: 'post'
        },
        dataSubmit: { // 提交
          url: '/sysback/supplyarea/batchRecover',
          type: 'post'
        },
        getExistInfo: { // 获取已有信息 by recordNo单据号
          url: '/sysback/supplyarea/getUpdateDetailByRecordNo',
          type: 'post'
        }
      }
    }
  },
  mounted () {
    this.loadInitDataInMounted();
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
    ...mapState('commonComps/basicAssociatedDialog', [
      'associatedRowList'
    ])
  },
  methods: {
    ...mapMutations('commonComps/basicAssociatedDialog', [
      'CANCEL_GOODS'
    ]),
    // 当前集合为空
    isEmptyForCurrentList (list = this.tableInfo.list) {
      return list.length === 0;
    },
    // 高级关联
    handleSeniorLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('高级关联'));
      this.seniorLinked.visible = true;
    },
    // 关联商品
    handleGoodsLinked () {
      sessionStorage.setItem('buttonId', getBtnsId('关联商品'));
      this.goodsLinked.visible = true;
    },
    // 删除表格row
    handleDeleteTableRow ({ row }) {
      if (this.seniorLinked.isSenior) {
        this.deleteDataBySeniorLinked(row);
      } else {
        this.deleteDataByGoodsLinked(row);
      }
    },
    // 删除数据 by 关联商品
    deleteDataByGoodsLinked (row) {
      this.CANCEL_GOODS({ row, type: this.goodsLinked.dimensionKey });
      this.tableInfo.list = this.tableInfo.list.filter(
        item => item.uuid !== row.uuid
      );
    },
    // 删除数据 by 高级关联
    deleteDataBySeniorLinked (row) {
      // 供应商+SKU+城市 维度
      this.tableInfo.list = this.tableInfo.list.filter(
        item => (item.supplyUuid + item.skuNo + item.saleCityUuid) !== (row.supplyUuid + row.skuNo + row.saleCityUuid)
      );
    },
    // 提交
    handleSubmit () {
      if (this.isEmptyForCurrentList()) {
        return this.$message.warning('请先关联商品');
      }
      if (this.tableInfo.list.length > BATCH_RESTORE_SUPPLY) {
        return this.$message.warning(`当前单据提交的行数不能超过${BATCH_RESTORE_SUPPLY}`);
      }
      this.postRequestSubmit({
        ...this.apiObj.dataSubmit,
        data: {
          uuidList: this.tableInfo.list.map(item => item.uuid).filter(item => item),
          launchReason: this.launchReason // 发起原因字段
        }
      }).then(retStatus => {
        if (retStatus) {
          this.$message.success('提交成功');
          this.$router.push({ name: 'chageFromManageList' });
        }
      });
    },
    // 清空表格
    clearTableData () {
      this.tableInfo.list = [];
    },
    // 在mounted时期加载初始数据
    loadInitDataInMounted () {
      const { recordNo } = this.$route.query;
      if (recordNo) {
        this.getExistTableDataByRecordNo(recordNo);
      }
    },
    // 获取表格数据 by reduce方法重组
    getTableDataByReducedWork (dataSource) {
      return dataSource.reduce((value, item) => {
        value.push({
          ...item,
          supplyName: item?.supplyInfoDTO?.supplyName,
          specDetailStr: item?.supplyProductInfo?.specDetailStr,
          supplyManagerArea: item?.supplyInfoDTO?.supplyManagerArea,
          manageAreaName: item?.supplyProductInfo?.manageArea
        })
        return value;
      }, []);
    },
    // 获取已有信息 by 单据号
    getExistTableDataByRecordNo (recordNo) {
      const { url, type } = this.apiObj.getExistInfo;
      this.postRequestTableData({ url: `${url}?recordNo=${recordNo}`, type }).then(retData => {
        if (retData) {
          this.tableInfo.list = this.getTableDataByReducedWork(retData.nowPriceRatio);
          this.footerFields = retData.recordDetail;
          this.launchReason = retData.launchReason; // 设置发起原因回显
        }
      })
    },
    // 获取表格数据 by 高级关联
    getTableDataBySeniorLinked (mappingList) {
      this.seniorLinked.isSenior = true;
      this.postRequestTableData({
        ...this.apiObj.getTableData,
        data: { mappingList }
      }).then(retData => {
        if (retData) {
          this.tableInfo.list = retData || [];
        }
      });
    },
    // 获取表格数据 by 关联商品
    getTableDataByGoodsLinked () {
      this.seniorLinked.isSenior = false;
      const uuidList = getListByMapDimensionKey(this.associatedRowList);
      if (this.isEmptyForCurrentList(uuidList)) {
        this.tableInfo.list = [];
        return false;
      }
      this.postRequestTableData({
        ...this.apiObj.getTableData,
        data: { uuidList }
      }).then(retData => {
        if (retData) {
          this.tableInfo.list = retData || [];
        }
      });
    },
    // 获取表格数据post请求
    async postRequestTableData ({ url, type, data = {}, isFormData = false }) {
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          return res.retData;
        }
        this.clearTableData();
      } catch (err) {
        this.clearTableData();
        this.tableInfo.loading = false;
      }
    },
    // 提交post请求
    async postRequestSubmit ({ url, type, data = {}, isFormData = false }) {
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(url, type, data, isFormData);
        this.btnLoading.submit = false;
        if (isResponseSuccessState(res.retStatus)) {
          return true;
        }
      } catch (err) {
        this.btnLoading.submit = false;
      }
    },
  }
}
</script>
<style lang="less" scoped>
.warning_title {
  color: #F56C6C;
}
</style>
